﻿using Dynamics.NAV.Metro.Common;
using Okra.Data;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dynamics.NAV.Metro.Data
{
    [Export(typeof(INavGLEntryDataSource))]
    [Shared]
    public class NavGLEntryDataSource : INavGLEntryDataSource
    {
        private IList<NavGLEntry> _glEntries;
        private NavGLEntryDataListSource _dataListSource;
        private NavCompany _currCompany;

        public NavGLEntryDataSource()
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                _glEntries = (IList<NavGLEntry>)new List<NavGLEntry>();
                _glEntries.Add(new NavGLEntry() { Index = 0, Description = "John", EntryNo = "1234" });
                _glEntries.Add(new NavGLEntry() { Index = 1, Description = "Brian", EntryNo = "5678" });
                _glEntries.Add(new NavGLEntry() { Index = 2, Description = "Jesper", EntryNo = "9837" });
                _glEntries.Add(new NavGLEntry() { Index = 3, Description = "Kenneth", EntryNo = "893489" });
                _glEntries.Add(new NavGLEntry() { Index = 4, Description = "Michael", EntryNo = "9984" });
            }
        }

        [Import]
        public IDynamicsNavApi NavApi { get; set; }

        public IList<NavGLEntry> GetGLEntries(NavGLAccount glAccount)
        {
            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
                return _glEntries;

            _currCompany = NavApi.CurrentCompany;
            _glEntries = null;
            _dataListSource = null;

            if (_dataListSource == null)
                _dataListSource = new NavGLEntryDataListSource(string.Format("G_L_Account_No_FilterOnly eq '{0}'", glAccount.No));

            // Create a single instance of the customer list
            // This can then be shared between multiple view models
            if ((_dataListSource != null) && (_glEntries == null))
            {
                _glEntries = (IList<NavGLEntry>)new VirtualizingDataList<NavGLEntry>(_dataListSource);
            }

            return _glEntries;
        }
    }
}
